//
//  Helper.m
//  IndonesiaBilingual
//
//  Created by ysx on 2023/12/8.
//

#import "Helper.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>

@implementation Helper

#pragma 获取总内存大小
+ (NSString *)getTotalMemorySize{
    long long totalMemorySize = [NSProcessInfo processInfo].physicalMemory;
    return [self fileSizeToString:totalMemorySize];
}

#pragma 获取当前可用内存
+ (NSString *)getAvailableMemorySize {
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return @"内存查找失败";
    }
    long long availableMemorySize = ((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count));
    return [self fileSizeToString:availableMemorySize];
}

#pragma 获取总磁盘容量
+ (NSString *)getTotalDiskSize {
    struct statfs buf;
    unsigned long long totalDiskSize = -1;
    if (statfs("/var", &buf) >= 0) {
        totalDiskSize = (unsigned long long)(buf.f_bsize * buf.f_blocks);
    }
    return [self fileSizeToString:totalDiskSize];
}

#pragma 获取可用磁盘容量  f_bavail 已经减去了系统所占用的大小，比 f_bfree 更准确
/*
+ (NSString *)getAvailableDiskSize {
    
    struct statfs buf;
    unsigned long long availableDiskSize = -1;
    if (statfs("/var", &buf) >= 0) {
        availableDiskSize = (unsigned long long)(buf.f_bsize * buf.f_bavail);
    }
    return [self fileSizeToString:availableDiskSize];
}*/
#pragma mark - 获取可用磁盘容量
+ (NSString *)getNewFreeSize {

    NSError *error = nil;
        NSDictionary *results = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
        if(error){return @"-1";}
    
        return [NSString stringWithFormat:@"%@",results[NSURLVolumeAvailableCapacityForImportantUsageKey]];
}

+ (NSString *)fileSizeToString:(unsigned long long)fileSize {
    NSInteger KB = 1024;
    NSInteger MB = KB*KB;
    NSInteger GB = MB*KB;
    
//    if (fileSize < 10)  {
//        return @"0 B";
//    }else if (fileSize < KB) {
//        return @"< 1 KB";
//    }else if (fileSize < MB) {
//        return [NSString stringWithFormat:@"%.2f KB",((CGFloat)fileSize)/KB];
//    }else if (fileSize < GB) {
//        return [NSString stringWithFormat:@"%.2f MB",((CGFloat)fileSize)/MB];
//    }else {
//         return [NSString stringWithFormat:@"%.2f GB",((CGFloat)fileSize)/GB];
//    }
    return [NSString stringWithFormat:@"%llu",(fileSize)];
}

+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 2; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

//获取设备IP地址
+(NSString *)getDeviceIPAddresses{
    int sockfd = socket(AF_INET,SOCK_DGRAM, 0);
    // if (sockfd <</span> 0) return nil;

    NSMutableArray *ips = [NSMutableArray array];

    int BUFFERSIZE =4096;
    struct ifconf ifc;
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            int len =sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                len = ifr->ifr_addr.sa_len;
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family !=AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;
            
            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;
            
            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;
 
            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            [ips addObject:ip];
        }
    }
    close(sockfd);
 
    NSString *deviceIP =@"";
    
    for (int i=0; i < ips.count; i++){
        if (ips.count >0){
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    
    return deviceIP;
}
@end
